import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
Vue.use(VueRouter);
import Store from '@/store'

let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
//重写
VueRouter.prototype.push = function (location, resolve, reject) {
    if (reject && resolve) {
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, () => { }, () => { })
    }

}
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (reject && resolve) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }

}
//配置
let router = new VueRouter(
    {
        routes,
        scrollBehavior(to, from, savedPosition) {
            // return 期望滚动到哪个的位置
            return { y: 100 };
        }
    });
//全局守卫：前置守卫
router.beforeEach(async (to, from, next) => {
    next();//放行函数
    let name = Store.state.user.userInfo.name
    let token = Store.state.user.token
    if (token) {
         //用户已登录还想去login
        if (to.path == '/login'||to.path=='/register') {
            next('/')
        } else {
            //去别的页面
            //用户名已有
            if (name) {
                next()
            } else {
                //没有用户信息，派发action跳转
                try {
                    //获取用户信息成功
                    await Store.dispatch("getUserInfo");
                    next();
                } catch (error) {
                    await Store.dispatch("userLogout");
                    next('/login')
                }

            }
        }
    } else {
         //未登录：不能去交易相关、不能去支付相关【pay|paysuccess】、不能去个人中心
      //未登录去上面这些路由-----登录
      let toPath = to.path;
      if(toPath.indexOf('/trade')!=-1 || toPath.indexOf('/pay')!=-1||toPath.indexOf('/center')!=-1){
        //把未登录的时候向去而没有去成的信息，存储于地址栏中【路由】
        next('/login?redirect='+toPath);
      }else{
         //去的不是上面这些路由（home|search|shopCart）---放行
         next();
      }
    }
})
export default router;